package cn.shop.cloud.ws;

import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: work
 * @ClassName WebSocketServer
 * @description:
 * @author: 李尧坤
 * @create: 2025−01-10 13:43
 * @Version 1.0
 **/

@Getter
@Setter
@Component
@ServerEndpoint("/{uuid}")
public class WebSocketServer {
    //使用线程安全的 hashmap
    public static ConcurrentHashMap<String,WebSocketServer> clients = new ConcurrentHashMap<>();

    //会话
    private Session session;


    /**
     *  浏览器和服务器建立连接的时候会调用这个方法
     * @param session
     * @param uuid
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("uuid") String uuid){
        System.out.println("客户端"+uuid+"建立了连接....");
        this.session = session;
        clients.put(uuid,this);
    }

    /**
     * 做动作时执行
     * @param msg
     * @param uuid
     */
    @OnMessage
    public void onMessage(String msg,@PathParam("uuid") String uuid){
        System.out.println("客户端"+uuid+"说了:"+msg);
    }

    /**
     *  关闭时执行
     * @param uuid
     */
    @OnClose
    public void onClose(@PathParam("uuid") String uuid){
        System.out.println("客户端"+uuid+"被移除了...");
        //移除
        clients.remove(uuid);

    }

    /**
     * 出错时执行
     * @param throwable
     */
    @OnError
    public  void onError(Throwable throwable){
        //打印信息
        throwable.printStackTrace();
    }
}
